package net.haveraid.service;

import java.util.List;

import net.haveraid.dao.RaidDAO;
import net.haveraid.data.Member;
import net.haveraid.data.Player;
import net.haveraid.data.Raid;
import net.haveraid.data.RaidCalendar;

import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class RaidServiceImpl implements RaidService {

	@Autowired
	private RaidDAO raidDAO;
	
	@Override
	@Transactional
	public List<Raid> getAll() {
		return raidDAO.getRaids();
	}
	
	@Transactional
	public List<Raid> getAll(Interval interval) {
		return raidDAO.getRaids(interval);
	}
	
	@Transactional
	public Raid get(Integer id) {
		return raidDAO.get(id);
	}

	@Transactional
	public void add(Raid raid) {
		raidDAO.save(raid);
	}

	@Override
	@Transactional
	public RaidCalendar getRaidCalendar() {
		DateTime st = DateTime.now().withDayOfWeek(1);
		DateTime start = st.minusWeeks(1);
		DateTime end = st.plusWeeks(2).minusDays(1);
		List<Raid> raids = getAll(new Interval(start, end));

		return new RaidCalendar(start, end, raids);
	}
	
	@Transactional
	public void signUpMember(Raid raid, Player player, Member.Type type) {
		Member m = new Member();
		m.setType(type);
		m.setStatus(Member.Status.Available);
		raid.getMembers().add(m);
		raidDAO.save(raid);
	}
	
	@Transactional
	public void signDownMember(Raid raid, Player player) {
		Member m = new Member();
		m.setType(null);
		m.setStatus(Member.Status.Unavailable);
		raid.getMembers().add(m);
		raidDAO.save(raid);
	}
	
}
